//   Copyright 2009
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.navjagpal.notes;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * Main activity for interacting with a single list.
 * 
 * @author nav@gmail.com (Nav Jagpal).
 *
 */
public class NoteListActivity extends ListActivity {

  private long mListId;
  private static final int MENU_NEW_NOTE = 0;
  private static final int DIALOG_NEW_NOTE = 0;
  private static final int CONTEXT_EDIT = 0;
  private static final int CONTEXT_DELETE = 1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    mListId = ContentUris.parseId(intent.getData());
    Cursor cursor = managedQuery(
        NotesProvider.Note.CONTENT_URI,
        new String[] {
            NotesProvider.Note.Columns._ID,
            NotesProvider.Note.Columns.TITLE},
            NotesProvider.Note.Columns.LIST_ID + "= ?",
            new String[] {"" + mListId},
            NotesProvider.Note.Columns.TITLE
    );
    ListAdapter adapter = new SimpleCursorAdapter(
        this, R.layout.notelist, cursor,
        new String[] {NotesProvider.Note.Columns.TITLE},
        new int[] {R.id.title});
    setListAdapter(adapter);
    registerForContextMenu(getListView());
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, MENU_NEW_NOTE , 0, R.string.new_note);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case MENU_NEW_NOTE:
        showDialog(DIALOG_NEW_NOTE);
        break;
    }
    return false;
  }

  private Dialog getNoteDialog(final long id) {
    Cursor c = managedQuery(
        NotesProvider.Note.CONTENT_URI,
        new String[] {
            NotesProvider.Note.Columns.TITLE,
            NotesProvider.Note.Columns.CONTENTS
        }, NotesProvider.Note.Columns._ID + "=?",
        new String[] {"" + id}, null);
    c.moveToFirst();
    final View layout = getLayoutInflater().inflate(R.layout.newnote_dialog,
        (ViewGroup) findViewById(R.id.layout_root));
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(layout);
    dialog.setTitle(R.string.new_note);
    Button saveButton = 
      (Button) layout.findViewById(R.id.save_button);
    final EditText titleEditText =
      (EditText) layout.findViewById(R.id.title); 
    final EditText contentsEditText =
      (EditText) layout.findViewById(R.id.contents);
    if (c.moveToFirst()) {
      titleEditText.setText(c.getString(
          c.getColumnIndex(NotesProvider.Note.Columns.TITLE)));
      contentsEditText.setText(c.getString(
          c.getColumnIndex(NotesProvider.Note.Columns.CONTENTS)));
    }
    saveButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        ContentValues values = new ContentValues();
        values.put(
            NotesProvider.Note.Columns.TITLE,
            titleEditText.getText().toString());
        values.put(
            NotesProvider.Note.Columns.CONTENTS,
            contentsEditText.getText().toString());
        values.put(
            NotesProvider.Note.Columns.LIST_ID,
            mListId);
        values.put(
            NotesProvider.Note.Columns.LAST_MODIFIED,
            System.currentTimeMillis() / 1000);
        if (id == -1) {
          getContentResolver().insert(
              NotesProvider.Note.CONTENT_URI, values);
        } else {
          getContentResolver().update(
              NotesProvider.Note.CONTENT_URI, values,
              NotesProvider.Note.Columns._ID + "= ?",
              new String[] {"" + id});
          getContentResolver().notifyChange(
              ContentUris.withAppendedId(NotesProvider.Note.CONTENT_URI, id),
              null);
        }
        dialog.dismiss();
      }
    });
    Button cancelButton =
      (Button) layout.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        dialog.dismiss();
      }
    });
    return dialog;
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    switch (id) {
      case DIALOG_NEW_NOTE:
        final View layout = getLayoutInflater().inflate(R.layout.newnote_dialog,
            (ViewGroup) findViewById(R.id.layout_root));
        dialog = getNoteDialog(-1);
        break;
    }
    return dialog;
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO(nav): We are always doing the query when clicked. Should be smarter
    // than that. Perhaps only query after some period of time.
    TextView contentsView = (TextView) v.findViewById(R.id.contents);
    if (contentsView.getVisibility() == View.GONE) {
      Cursor cursor = managedQuery(
          NotesProvider.Note.CONTENT_URI,
          new String[] {NotesProvider.Note.Columns.CONTENTS},
          NotesProvider.Note.Columns._ID + "= ?", new String[] {"" + id}, null
      );
      if (cursor.moveToFirst()) {
        contentsView.setText(cursor.getString(0));
      }
      contentsView.setVisibility(View.VISIBLE);
    } else {
      contentsView.setVisibility(View.GONE);
    }
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, CONTEXT_EDIT, 0, R.string.edit);
    menu.add(0, CONTEXT_DELETE, 0, R.string.delete);
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
      case CONTEXT_EDIT:
        Dialog dialog = getNoteDialog(info.id);
        dialog.setOwnerActivity(this);
        dialog.show();
        return true;
      case CONTEXT_DELETE:
        deleteNote(info.id);
    }
    return false;
  }

  private void deleteNote(long id) {
    getContentResolver().delete(
        NotesProvider.Note.CONTENT_URI,
        NotesProvider.Note.Columns._ID + "=?",
        new String[] {"" + id});
  }

}
